 package com.financing.service.invest;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import com.financing.enums.invest.InvestLogType;
import com.financing.model.invest.InvestLog;
import com.financing.service.BaseService;
import com.financing.util.Money;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class InvestLogService extends BaseService<InvestLog>{

	/**
	 * 新增交易记录
	 */
	public static void build(String name, InvestLogType type, int itemid, double amount, int userId, String status, String summary, String code) {
		InvestLog log = new InvestLog();
		log.setName(name);
		log.setItemId(itemid);  
		log.setMode(type.getMode());
		log.setType(type.getType());
		log.setAmount(amount);
		log.setUserId(userId);
		log.setCreateTime(new Date());
		log.setStatus(status);
		log.setSummary(summary);
		log.setCode(code);
		log.save();
	}
	
	/**
	 * 修改记录状态为生效
	 */ 
	public static void success(String type, int itemId, String summary) {
		Db.update("update invest_log set status = 'success', summary=? where type=? AND item_id = ?", summary, type, itemId);
	}
	
	/**
	 * 修改记录状态为失败
	 */ 
	public static void failed(String type, int itemId, String summary) {
		Db.update("update invest_log set status = 'failed', summary=? where type=? AND item_id = ?", summary, type, itemId);
	}
	
	/**
	 * 根据类型获取数据
	 * @return 
	 */
	public double totalFriendShare(int userId) {
		InvestLog log = InvestLog.me.findFirst("select SUM(amount) as total from invest_log where user_id=? AND status='success' AND type='share' AND summary='friend'", userId);
		return Money.get(log.get("total"));
	}
	
	
	/**
	 * 分页数据
	 */
	public Page<InvestLog> list(int page, int size, Map<String, String> map) {
		return InvestLog.me.paginate(page, size, buildSql("invest_log",Arrays.asList("item_id", "create_time", "type", "status", "user_id"),map));
	}
}
